package com.zzz.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    public String paymentInfoOk() {
        return Thread.currentThread() + "_OK";
    }

    @HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfoTimeOut() {
        //int a = 10 / 0;
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread() + "111_TimeOut";
    }

    public String paymentInfoTimeOutHandler() {
        return "运行超时或者出错";
    }

    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerHandler",  commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled", value="true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="10000"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="50"),
    })
    public String paymentCircuitBreaker(Long id) {
        if(id != null && id > 0) {
            return "OK 正常 " + id;
        }
        throw new RuntimeException("出现异常了！！！ Exception");
    }

    public String paymentCircuitBreakerHandler(Long id) {
        return "CircuitBreaker 兜底方案！" + id;
    }
}
